package com.thinkverse.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.thinkverse.user.dto.ChangePasswordRequestDTO;
import com.thinkverse.user.dto.UpdateUserRequestDTO;
import com.thinkverse.user.entity.User;
import com.thinkverse.user.mapper.UserMapper;
import com.thinkverse.user.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public User getCurrentUser(Long userId) {
        User u = userMapper.selectById(userId);
        if (u == null) {
            throw new RuntimeException("用户不存在");
        }
        // 隐去密码
        u.setPassword(null);
        return u;
    }

    @Override
    @Transactional
    public void updateUserInfo(Long userId, UpdateUserRequestDTO request) {
        User user = userMapper.selectById(userId);
        if (user == null) throw new RuntimeException("用户不存在");
        if (request.getUsername() != null) user.setUsername(request.getUsername());
        if (request.getInstitution() != null) user.setInstitution(request.getInstitution());
        if (request.getAvatar() != null) user.setAvatar(request.getAvatar());
        user.setUpdatedAt(java.time.LocalDateTime.now());
        userMapper.updateById(user);
    }

    @Override
    @Transactional
    public void changePassword(Long userId, ChangePasswordRequestDTO request) {
        User user = userMapper.selectById(userId);
        if (user == null) throw new RuntimeException("用户不存在");
        if (!passwordEncoder.matches(request.getOldPassword(), user.getPassword())) {
            throw new RuntimeException("原密码错误");
        }
        user.setPassword(passwordEncoder.encode(request.getNewPassword()));
        user.setUpdatedAt(java.time.LocalDateTime.now());
        userMapper.updateById(user);
    }

    @Override
    public List<User> listUsers(int page, int size) {
        Page<User> p = new Page<>(page, size);
        Page<User> res = userMapper.selectPage(p, new QueryWrapper<>());
        res.getRecords().forEach(u -> u.setPassword(null));
        return res.getRecords();
    }
}
